'use strict';

/**
 * 字典项服务
 */
const Service = require('egg').Service;

class DictItemService extends Service {
  /**
   * 创建字典项
   * @param {Object} dictItemData - 字典项数据
   * @return {Promise<Object>} 创建的字典项
   */
  async create(dictItemData) {
    const { ctx } = this;
    return ctx.model.DictItem.create(dictItemData);
  }

  /**
   * 查询字典项列表
   * @param {Object} query - 查询条件
   * @param {Number} page - 页码
   * @param {Number} pageSize - 每页数量
   * @return {Promise<Object>} 字典项列表和总数
   */
  async list(query = {}, page = 1, pageSize = 10) {
    const { ctx } = this;
    const offset = (page - 1) * pageSize;
    const where = {};

    if (query.dictTypeId) {
      where.dictTypeId = query.dictTypeId;
    }

    if (query.label) {
      where.label = { [ctx.Sequelize.Op.like]: `%${query.label}%` };
    }

    if (query.value) {
      where.value = { [ctx.Sequelize.Op.like]: `%${query.value}%` };
    }

    if (query.status !== undefined && query.status !== '') {
      where.status = query.status;
    }

    const { count, rows } = await ctx.model.DictItem.findAndCountAll({
      where,
      offset,
      limit: pageSize,
      order: [[ 'sort', 'ASC' ]],
      include: [
        { model: ctx.model.DictType, as: 'dictType', attributes: [ 'id', 'name', 'code' ] },
      ],
    });

    return {
      list: rows,
      total: count,
      page,
      pageSize,
    };
  }

  /**
   * 查询单个字典项
   * @param {string} id - 字典项ID
   * @return {Promise<Object>} 字典项信息
   */
  async findById(id) {
    const { ctx } = this;
    return ctx.model.DictItem.findByPk(id, {
      include: [
        { model: ctx.model.DictType, as: 'dictType', attributes: [ 'id', 'name', 'code' ] },
      ],
    });
  }

  /**
   * 更新字典项
   * @param {string} id - 字典项ID
   * @param {Object} dictItemData - 更新的字典项数据
   * @return {Promise<Object>} 更新后的字典项
   */
  async update(id, dictItemData) {
    const { ctx } = this;
    const dictItem = await this.findById(id);
    if (!dictItem) {
      ctx.throw(404, '字典项不存在');
    }

    return dictItem.update(dictItemData);
  }

  /**
   * 删除字典项
   * @param {string} id - 字典项ID
   * @return {Promise<Boolean>} 是否删除成功
   */
  async destroy(id) {
    const { ctx } = this;
    const dictItem = await this.findById(id);
    if (!dictItem) {
      ctx.throw(404, '字典项不存在');
    }

    return dictItem.destroy();
  }

  /**
   * 更新字典项状态
   * @param {string} id - 字典项ID
   * @param {boolean} status - 状态
   * @return {Promise<Object>} 更新后的字典项
   */
  async updateStatus(id, status) {
    const { ctx } = this;
    const dictItem = await this.findById(id);
    if (!dictItem) {
      ctx.throw(404, '字典项不存在');
    }

    dictItem.status = status;
    return dictItem.save();
  }

  /**
   * 根据字典类型编码获取字典项
   * @param {String} dictTypeCode - 字典类型编码
   * @param {string} status - 字典项状态
   * @return {Promise<Array>} 字典项列表
   */
  async getByDictTypeCode(dictTypeCode, status) {
    const { ctx } = this;
    if (!dictTypeCode) {
      ctx.throw(400, '字典类型编码不能为空');
    }

    const dictType = await ctx.model.DictType.findOne({
      where: { code: dictTypeCode, status: true },
    });

    if (!dictType) {
      return [];
    }

    const where = { dictTypeId: dictType.id };
    if (status !== undefined && status !== '') {
      where.status = status;
    }

    return ctx.model.DictItem.findAll({
      where,
      order: [[ 'sort', 'ASC' ]],
    });
  }

  /**
   * 批量创建或更新字典项
   * @param {string} dictTypeId - 字典类型ID
   * @param {Array} items - 字典项数组
   * @return {Promise<Boolean>} 是否成功
   */
  async batchCreateOrUpdate(dictTypeId, items) {
    const { ctx } = this;
    // 先删除该字典类型下的所有字典项
    await ctx.model.DictItem.destroy({
      where: { dictTypeId },
    });

    // 批量创建新的字典项
    const dictItems = items.map(item => ({
      dictTypeId,
      label: item.label,
      value: item.value,
      sort: item.sort || 0,
      status: item.status !== undefined ? item.status : true,
    }));

    await ctx.model.DictItem.bulkCreate(dictItems);
    return true;
  }
}

module.exports = DictItemService;
